import React, { Component } from 'react';
import   { post }  from '../../utils/post'
import { 
    Modal,  
    Form,
    Input,
    Select,
    DatePicker,
    Button,
    Space,
    message,
    Upload
   } from 'antd';
   import {
    PictureTwoTone,
    LoadingOutlined, PlusOutlined
} from "@ant-design/icons";
// import { withFormik, Form, Field, ErrorMessage } from 'formik'
// import * as Yup from 'yup'
import styles from '../editor/editor.module.css'
function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }
  

const beforeUpload = (file) =>{
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('你只能上传 JPG/PNG 格式!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小必须小于2MB!');
    }
    return isJpgOrPng && isLt2M;
  }

class Editor extends Component {
    componentWillReceiveProps(nextProps) {
        this.setState({
            isShow: nextProps.isShow
        });
    }
    constructor() {
        super(...arguments)
        this.state = {
            isShow: false,
            nickname: '',
            profile: '',
            email:'',
            sex: true,
            date: '',
            age: JSON.parse(localStorage.getItem('usersMessage')).age,
            _id: JSON.parse(localStorage.getItem('usersMessage'))._id,
            username: JSON.parse(localStorage.getItem('usersMessage')).username,
            loading: false
        }
    }

// 保存date
     saveDate = (date, dateString)=> {
         console.log(date,dateString);
         const now = new Date()
         const year = now.getFullYear()
         const age = year - dateString.slice(0,4)
         this.setState({
             date: dateString,
             age: age
         })
  }

// 保存nickname
     saveNickName = (e) =>{
        let nickname = e.target.value
        if(nickname.length > 6){
            message.info('昵称长度不能大于6')
            return
        }
        this.setState({
            nickname: nickname
        })
     }

// 保存个人介绍
     saveProFile = (e) =>{
         let profile = e.target.value
         if(profile.length >20){
             message.info('个人简介不能超过20字')
             return
         }
         this.setState({
             profile: e.target.value
         })
     }

// 保存性别
     saveSex = (e) =>{
         console.log('让我看看性别的变化',e);
        this.setState({
            sex: e
        })
     }

// 保存邮箱
     saveEmail = (e) =>{
         this.setState({
             email: e.target.value
         })
     }

// 提交
     onFinish = async(e) =>{
        const {_id,nickname,sex,age,profile,email,date,username,imageUrl } = this.state
        console.log('这是提交上去的',sex);
        const res = await post('/api/editor',{
            _id,
            nickname,
            sex,
            age,
            profile,
            email,
            date,
            username,
            imageUrl
        })
        const data = res.data.data.userInfo
        console.log('后端返回的数据',data);
        if(res.data.meta.status == 200 ){
             (()=>{
                message.info('修改成功!')
            })()
            let usersMessage = {
                _id: data._id,
                username: data.username,
                nickname: data.nickname ? data.nickname : `用户${username}`,
                sex: JSON.parse(data.sex) ? '男' : '女' ,
                avater: data.avater ? data.avater : 'https://img0.baidu.com/it/u=1329709505,2760911286&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800',
                profile: data.profile ? data.profile : '该用户很懒，没有做自我介绍',
                email:data.email ? data.email : '该用户没有留下邮箱地址' ,
                date: data.date ? data.date : '未知',
                age: data.age ? data.age : 18,
                createdAt: data.createdAt,
                updatedAt: data.updatedAt
            }
            localStorage.setItem('usersMessage',JSON.stringify(usersMessage))
        }
       
        
        
     }
// 失败提交
     onFinishFailed = (e) =>{
         console.log('Failed:',e);
     }
    
     handleChange = info => {
        if (info.file.status === 'uploading') {
          this.setState({ loading: true });
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
        //   getBase64(info.file.originFileObj, imageUrl =>
        //     this.setState({
        //       imageUrl,
        //       loading: false,
        //     }),
        //   );
        console.log('提交的照片',info.file.response.url);
        this.setState({
            imageUrl: info.file.response.url
        })
        }
      }; 

     
    render() {
        const { loading, imageUrl} = this.state
        const uploadButton = (
            <div>
              {loading ? <LoadingOutlined /> : <PlusOutlined />}
              <div style={{ marginTop: 8 }}>上传</div>
            </div>
          );
        return (
            <div>
                <Modal
                    title="编辑个人资料"
                    centered
                    visible={this.state.isShow}
                    onOk={() => this.props.changShow(false)}
                    onCancel={() => this.props.changShow(false)}
                    width={600}
                >
                    <Form
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 14 }}
                        layout="horizontal"
                        initialValues={{ size: this.state.size }}
                        size={this.state.size}
                        onFinish={this.onFinish}
                        onFinishFailed={this.onFinishFailed}
                    >
                        <Form.Item label="头像">
                            <Upload 
                            name = 'file'
                            action = "http://127.0.0.1:3000/api/fileImg"
                            listType = 'picture-card'
                            beforeUpload ={beforeUpload}
                            onChange = {this.handleChange} >
                                 {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                            </Upload>
                        </Form.Item>
                        <Form.Item label="昵称">
                            <Input value={this.state.nickname} placeholder="请输入昵称" onChange={this.saveNickName}/>
                        </Form.Item>
                        <Form.Item label="性别">
                            <Select onChange={this.saveSex}>
                                <Select.Option value="true">男</Select.Option>
                                <Select.Option value="false">女</Select.Option>
                            </Select>
                        </Form.Item>
                        <Form.Item label="邮箱地址">
                            <Input value={this.state.email} type="email" placeholder="请输入邮箱" onChange={this.saveEmail} />
                        </Form.Item>
                        <Form.Item label="个人简介">
                            <Input placeholder='20字以内哦～' value={this.state.profile} onChange={this.saveProFile}/>
                        </Form.Item>
                        <Form.Item label="生日">
                            <Space>
                                <DatePicker onChange={this.saveDate}/>
                            </Space>
                        </Form.Item>
                        <Form.Item label="年龄">
                            {this.state.age}
                        </Form.Item>
                        <Form.Item label='确认修改'>
                        <Button type="primary" htmlType="submit">修改</Button>
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        );
    }
}


export default Editor;
